import { Button, message, Modal, Space, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect, } from 'react';
import { Access, getDvaApp, history, useAccess, } from 'umi';

import $utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { getCellTrackList, } from '@/services/cabinet';
import { operationsData } from '@/utils/common';
import moment from 'moment';
import { ProFormInstance } from '@ant-design/pro-form';

const initDate = {
    startTime: moment().subtract(15, 'days').startOf('day'),     //  开始时间
    endTime: moment().endOf('day'),     //  结束时间
};

const CellTrack: React.FC = () => {
    // 获取权限
    const access = useAccess();

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;

    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();

    const [initParams, setParams] = useState<any>();
    const [current, setCurrent] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(20);

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/Cabinet');
    }

    useEffect(() => {
        if (!initParams) {
            const data = l_state?.params ? {
                ...l_state?.params,
                screenTime: [moment(l_state?.params.startTime) || initDate.startTime, moment(l_state?.params.endTime) || initDate.endTime],
            } : {
                ...initDate,
                screenTime: [initDate.startTime, initDate.endTime],
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
            screenTime: [initDate.startTime, initDate.endTime],
        };;
        if (JSON.stringify(data) === JSON.stringify(initParams)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    // 格口占用情况 
    const cellTrack_columns: ProColumns<any>[] = [
        {
            title: '时间',
            dataIndex: 'screenTime',
            align: 'center',
            hideInTable: true,
            valueType: 'dateRange',
            search: {
                transform: (value: any) => ({ startTime: value[0], endTime: value[1] }),
            },
            fieldProps: {
                showTime: false,
                disabledDate: (current: any) => {
                    // 只可选择90天内，上线日期后
                    return !(current > moment("11-23-2022", "MM-DD-YYYY").endOf('days') && current > moment().subtract(90, 'days') && current < moment().subtract(0, 'days').endOf('days'));
                },
                ranges: {
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    昨天: [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                        moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                        moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                }
            }
        },
        {
            title: '运单号',
            align: 'center',
            dataIndex: 'expCode',
        },
        {
            title: '操作人手机号',
            align: 'center',
            dataIndex: 'phone',
        },
        {
            title: '操作类型',
            align: 'center',
            dataIndex: 'operation',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: operationsData
            }
        },
        {
            title: '操作来源',
            align: 'center',
            search: false,
            dataIndex: 'sourceName',
        },
        {
            title: '操作结果',
            dataIndex: 'result',
            align: 'center',
            search: false,
            valueType: 'select',
            fieldProps: {
                options: [
                    {
                        label: '未知',
                        value: 0,
                    },
                    {
                        label: '成功',
                        value: 1,
                    },
                    {
                        label: '失败',
                        value: 2,
                    },
                ]
            }
        },
        {
            title: '操作时间',
            dataIndex: 'time',
            align: 'center',
            search: false,
            width: '100px',
        },
        {
            title: '服务器时间',
            dataIndex: 'createTime',
            align: 'center',
            search: false,
            width: '100px',
        },
    ];

    return (
        <PageContainer>
            {cur_id && initParams && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProTable
                    formRef={formRef}
                    actionRef={actionRef}
                    rowKey="cellType"
                    tableAlertRender={false}
                    pagination={{
                        pageSize: pageSize,
                        showSizeChanger: true,
                        size: 'small',
                        onShowSizeChange: (current, pageSize) => {
                            setPageSize(pageSize);
                        }
                    }}
                    form={{
                        initialValues: initParams
                    }}
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                        collapseRender: () => false,
                        span: {
                            xs: 8, sm: 8, md: 8, lg: 8, xl: 8, xxl: 8,
                        },
                        optionRender: (searchConfig, formProps, dom) => [
                            dom.reverse()[0],
                            <Button key="resetText" onClick={() => {
                                const data = {
                                    ...initDate,
                                    screenTime: [initDate.startTime, initDate.endTime],
                                };
                                setParams(data);
                            }}>
                                重置
                            </Button>,
                        ],
                    }}
                    toolBarRender={false}
                    columns={cellTrack_columns}
                    params={{ cellCode: l_state.data.code, cabId: l_state.data.cabinetId }}
                    request={async (params: any) => {
                        if (!params.startTime) { params.startTime = initDate.startTime.format('YYYY-MM-DD'); }
                        if (!params.endTime) { params.endTime = initDate.endTime.format('YYYY-MM-DD'); }
                        const msg = await getCellTrackList(params);
                        if (msg.code === 0) {
                            $utils.addTab(dispatch, {
                                name: `查看${l_state.data.desc}(${l_state.data.code})格口轨迹`,
                                path: '/BasicConfig/Cabinet/cellTrack',
                                isTopMenu: true,
                                state: {
                                    status: 'detail',
                                    data: l_state.data,
                                    params: params
                                }
                            });
                            setParams(params);
                        }
                        return {
                            data: msg.body.list || [],
                            success: msg.code === 0,
                            total: msg.body?.count,
                        }
                    }}
                />
            </ProCard>}
        </PageContainer >
    );
};

export default CellTrack;
